import React, { Component } from "react";
import BaseComponent from "@/components/BaseComponent";
import styles from "./index.less";
import { connect } from "dva";
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Popconfirm,
  Row,
  Select,
  Tabs
} from "antd";
import StandardTable from "@/components/StandardTable";
import AddView from "./AddView";
import EditView from "./EditView";
import PreviewView from "./PreviewView";
import { listByPage } from "@/services/articlesettingApi";
import moment from "moment";

const SearchFormItem = props => {
  const { form, children, fieldName } = props;
  const { getFieldDecorator } = form;
  return getFieldDecorator(fieldName, {})(children);
};
const { Option } = Select;
const { TabPane } = Tabs;

@connect(({ user, articlesetting, loading }) => ({
  currentUser: user.currentUser,
  data: articlesetting.data,
  isLoading: loading.effects["articlesetting/listByPage"],
  isCreating: loading.effects["articlesetting/create"],
  isUpdating: loading.effects["articlesetting/update"],
  isDeling: loading.effects["articlesetting/deleteById"]
}))
@Form.create()
class ArticleSetting extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 被选中的选显卡
      activeKey: "1",
      // 添加视图的可见性
      addVisible: false,
      // 预览页面的可见性
      previewVisible: false,
      // 编辑页面的可见性
      editVisible: false,
      // 别选中的记录
      record: {}
    };
  }

  columns = [
    {
      title: "编号",
      sorter: false,
      key: "col1",
      width: 80,
      render: (text, record, index) => {
        return `${index + 1}`;
      }
    },
    {
      title: "标题",
      sorter: false,
      key: "title",
      dataIndex: "title"
    },
    {
      title: "发布时间",
      sorter: false,
      key: "publish_time",
      render: (text, record, index) => {
        const { publish_time } = record;
        return publish_time
          ? moment(publish_time).format("YYYY-MM-DD HH:mm:ss")
          : "";
      }
    },
    {
      title: "发布人员",
      sorter: false,
      key: "username",
      dataIndex: "username"
    },
    {
      title: "操作",
      sorter: false,
      key: "operate",
      render: (text, record, index) => {
        return (
          <div>
            <a
              style={{ cursor: "pointer", marginRight: "16px" }}
              onClick={() => {
                this.handlePreviewClick(record);
              }}
            >
              详情
            </a>
            <a
              style={{ cursor: "pointer", marginRight: "16px" }}
              onClick={() => {
                this.handleEditClick(record);
              }}
            >
              编辑
            </a>
            <Popconfirm
              title="确定执行当前操作吗?"
              onConfirm={() => {
                this.handleDelClick(record);
              }}
            >
              <a
                type="link"
                size={"small"}
                style={{ cursor: "pointer", color: "red" }}
              >
                删除
              </a>
            </Popconfirm>
          </div>
        );
      }
    }
  ];

  listByPage = (params = {}) => {
    this.execHttp("articlesetting/listByPage", {
      group_id: this.state.activeKey,
      ...params
    });
  };

  create = data => {
    if (this.props.isCreating) {
      return;
    }
    const hide = this.loadingMessage("操作中,请稍后...");
    this.execHttp("articlesetting/create", {
      data: JSON.stringify(data)
    })
      .then(resp => {
        if (hide) {
          hide();
        }
        const { success } = resp;
        if (success) {
          this.successMessage("新增成功");
          this.setState({
            addVisible: false
          });
          // 刷新列表
          this.listByPage({});
        }
      })
      .catch(reason => {
        if (hide) {
          hide();
        }
      });
  };

  update = data => {
    if (this.props.isUpdating) {
      return;
    }
    const hide = this.loadingMessage("操作中,请稍后...");
    this.execHttp("articlesetting/update", {
      data: JSON.stringify(data)
    })
      .then(resp => {
        if (hide) {
          hide();
        }
        const { success } = resp;
        if (success) {
          this.successMessage("更新成功");
          this.setState({
            editVisible: false
          });
          // 刷新列表
          this.listByPage({});
        }
      })
      .catch(reason => {
        if (hide) {
          hide();
        }
      });
  };

  deleteById = id => {
    if (this.props.isDeling) {
      return;
    }
    const hide = this.loadingMessage("操作中,请稍后...");
    this.execHttp("articlesetting/deleteById", { id })
      .then(resp => {
        if (hide) {
          hide();
        }
        const { success } = resp;
        if (success) {
          this.successMessage("删除成功");
          // 刷新列表
          this.listByPage({});
        } else {
          this.errorMessage("删除失败");
        }
      })
      .catch(reason => {
        if (hide) {
          hide();
        }
      });
  };

  componentDidMount() {
    this.listByPage({});
  }

  render() {
    const { form } = this.props;
    return (
      <div className={styles.articleSetting}>
        <Card bordered={true} title={"文章管理"}>
          <Row gutter={16}>
            <Col span={6}>
              <SearchFormItem form={form} fieldName={"keyword"}>
                <Input
                  placeholder={"请输入关键字"}
                  allowClear
                  style={{ width: "200px" }}
                />
              </SearchFormItem>
            </Col>
            <Col
              span={18}
              className="gutter-row"
              style={{ textAlign: "right" }}
            >
              <Button style={{ marginLeft: 8 }} onClick={this.handleResetClick}>
                重置
              </Button>
              <Button
                type="primary"
                style={{ marginLeft: 8 }}
                onClick={this.handleSearchClick}
              >
                查询
              </Button>
              <Button
                type={"primary"}
                style={{ marginLeft: 8 }}
                onClick={this.handleAdd}
              >
                新增
              </Button>
            </Col>
          </Row>
        </Card>

        <Card bordered={true} style={{ marginTop: "16px" }}>
          <Tabs
            activeKey={this.state.activeKey}
            onChange={this.handleTabChange}
          >
            <TabPane tab={"最新信息"} key={"1"}></TabPane>
            <TabPane tab={"工作动态"} key={"2"}></TabPane>
            <TabPane tab={"公告通知"} key={"3"}></TabPane>
            <TabPane tab={`学术天地`} key={"4"}></TabPane>
          </Tabs>

          <StandardTable
            hasSelection={false}
            onChange={this.handleTableChange}
            selectedRows={[]}
            loading={this.props.isLoading}
            bordered
            data={this.props.data}
            columns={this.columns}
            rowKey="id"
          />
        </Card>
        {/*新增*/}
        {this.state.addVisible ? (
          <AddView
            onClose={this.handleAddViewClose}
            visible={this.state.addVisible}
            onSubmit={this.handleAddViewSubmit}
          ></AddView>
        ) : null}
        {/*详情*/}
        {this.state.previewVisible ? (
          <PreviewView
            record={this.state.record}
            onClose={this.handlePreviewViewClose}
            visible={this.state.previewVisible}
          ></PreviewView>
        ) : null}
        {/*编辑*/}
        {this.state.editVisible ? (
          <EditView
            record={this.state.record}
            onClose={this.handleEditViewClose}
            visible={this.state.editVisible}
            onSubmit={this.handleEditViewSubmit}
          ></EditView>
        ) : null}
      </div>
    );
  }

  /**提交新增数据*/
  handleAddViewSubmit = values => {
    this.create(values);
  };

  /*编辑数据*/
  handleEditViewSubmit = values => {
    this.update(values);
  };

  /**关闭抽屉*/
  handleAddViewClose = () => {
    this.setState({
      addVisible: false
    });
  };

  /**
   * 关闭抽屉
   */
  handlePreviewViewClose = () => {
    this.setState({
      previewVisible: false
    });
  };

  /**
   * 关闭抽屉
   */
  handleEditViewClose = () => {
    this.setState({
      editVisible: false
    });
  };

  handleTabChange = activeKey => {
    this.setState(
      {
        activeKey
      },
      () => {
        this.listByPage({});
      }
    );
  };

  /**
   * 重置
   */
  handleResetClick = () => {
    const { form } = this.props;
    form.resetFields();
    this.listByPage({});
  };

  /**
   * 查询
   */
  handleSearchClick = () => {
    const { form } = this.props;
    const data = form.getFieldsValue();
    this.listByPage({ ...data });
  };

  // 新增
  handleAdd = () => {
    this.setState({ addVisible: true });
  };

  // 详情
  handlePreviewClick = record => {
    this.setState({
      record: record,
      previewVisible: true
    });
  };
  // 编辑
  handleEditClick = record => {
    this.setState({
      record: record,
      editVisible: true
    });
  };
  // 删除
  handleDelClick = record => {
    this.deleteById(record.id);
  };

  handleTableChange = (pagination, filters, sorter) => {
    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize
    };
    this.listByPage(params);
  };
}

export default ArticleSetting;
